package com.chat.websocket;

import com.chat.websocket.domain.ChatInfoContainer;
import com.chat.websocket.domain.MemberInfo;
import com.chat.websocket.msg.MyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * @author 崔超
 * 2022/2/12
 */
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        MemberInfo info = ChatInfoContainer.getMemberInfo(ctx);
        //HttpRequestHandler中的普通Channel关闭也会触发此方法
        if (info == null) {
            super.channelInactive(ctx);
            return;
        }
        String sysMsg = MyMessage.systemTxt("用户【" + info.getNickName() + "】离开聊天室").toJson();
        ChatInfoContainer.sendMsgToChatRoom(ctx, sysMsg);
        ChatInfoContainer.leaveChatRoom(ctx);

        System.out.println("用户【" + info.getNickName() + "】离开聊天室");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            ctx.pipeline().remove(HttpRequestHandler.class);
            sendEnterRoomMsg(ctx);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        MemberInfo info = ChatInfoContainer.getMemberInfo(ctx);
        String text = msg.text();
        String jsonMsg;
        if (text.startsWith("data:image/jpeg;base64,") || text.startsWith("data:image/png;base64,")) {
            jsonMsg = MyMessage.userPic(info, text).toJson();
            System.out.println("图片传输");
        } else {
            jsonMsg = MyMessage.userTxt(info, text).toJson();
            System.out.println(text);
        }

        ChatInfoContainer.sendMsgToChatRoom(ctx, jsonMsg);

    }

    private void sendEnterRoomMsg(ChannelHandlerContext ctx) {
        MemberInfo info = ChatInfoContainer.getMemberInfo(ctx);
        String name = info.getNickName();
        System.out.println("用户【" + name + "】进入聊天室");
        long personCount = ChatInfoContainer.getPersonCountInCurRoom(ctx);
        String sysMsgToOthers = MyMessage.systemTxt("用户【" + name + "】加入聊天室").toJson();
        String sysMsgToTheOne = personCount == 1 ?
                MyMessage.systemTxt("欢迎你【" + name + "】，你是进入此聊天室的第一个人").toJson()
                : MyMessage.systemTxt("欢迎你【" + name + "】，当前聊天室共" + personCount + "人").toJson();

        ctx.writeAndFlush(new TextWebSocketFrame(sysMsgToTheOne));

        ChannelGroup channelGroup = ChatInfoContainer.getCurChannelGroup(ctx);
        String curId = ctx.channel().id().asLongText();
        channelGroup.stream()
                .filter(channel -> !channel.id().asLongText().equals(curId))
                .forEach(channel -> channel.writeAndFlush(new TextWebSocketFrame(sysMsgToOthers)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("TextWebSocketFrameHandler Exception:" + cause.getMessage());
    }
}
